package com.zy.edu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zy.edu.bean.*;
import com.zy.edu.config.SystemParam;
import com.zy.edu.dao.CourseChapterExercisesDao;
import com.zy.edu.service.CourseChapterExercisesService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zy.edu.service.CourseChapterExercisesStuService;
import com.zy.edu.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HuangHaiShui
 * @since 2021-07-28
 */
@Service
public class CourseChapterExercisesServiceImpl extends ServiceImpl<CourseChapterExercisesDao, CourseChapterExercises> implements CourseChapterExercisesService {

    @Resource
    UserService userService;


    @Resource
    CourseChapterExercisesStuService courseChapterExercisesStuService;
    @Override
    public Map saveOrUpdate(CourseChapterExercises courseChapterExercises, InputParam inputParam) throws Exception {

        if(StringUtils.isEmpty(courseChapterExercises.getChapterId())){
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }

        //当前用户的信息
        User currentUser = userService.selectById(inputParam.getUserId());
        //只有超管和校管可以上传课时
        if(currentUser.getRoleType().equals(Role.SUPER)
                ||currentUser.getRoleType().equals(Role.SCHOOL)) {
            saveOrUpdateOneData(courseChapterExercises);
            return ResponseInfo.success(null);
        }else {
            return ResponseInfo.error("您无权限创建课时");
        }
    }

    /**
     * @Author: HuangHaiShui 
     * @Description:创建或更改习题
     * @Date: 17:48 2021/8/1
     * @param courseChapterExercises: 
     * @return: void
     **/
    private void saveOrUpdateOneData(CourseChapterExercises courseChapterExercises) throws Exception {
        if(StringUtils.isEmpty(courseChapterExercises.getContent())
            ||StringUtils.isEmpty(courseChapterExercises.getAnswer())){
            throw new Exception(SystemParam.ERROR_PARAMS);
        }
        if (StringUtils.isEmpty(courseChapterExercises.getId())) {
            courseChapterExercises.setCreateTime(new Date());
            //答案大写
            courseChapterExercises.setStatus(1);
            courseChapterExercises.setAnswer(courseChapterExercises.getAnswer().toUpperCase());
            this.baseMapper.insert(courseChapterExercises);
        } else {
            courseChapterExercises.setAnswer(courseChapterExercises.getAnswer().toUpperCase());
            this.baseMapper.updateById(courseChapterExercises);
        }
    }

    @Override
    public Map batchSave(InputParam inputParam) throws Exception {
        //批量插入课时的练习题
        if(StringUtils.isEmpty(inputParam.getExerciseStr())
            ||StringUtils.isEmpty(inputParam.getChapterId())){
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }
        //当前用户的信息
        User currentUser = userService.selectById(inputParam.getUserId());
        //只有超管和校管可以上传课时
        if(currentUser.getRoleType().equals(Role.SUPER)
                ||currentUser.getRoleType().equals(Role.SCHOOL)) {

            List<CourseChapterExercises>  exercisesList = JSONObject.parseArray(inputParam.getExerciseStr(), CourseChapterExercises.class);
            for (CourseChapterExercises courseChapterExercises : exercisesList) {
                saveOrUpdateOneData(courseChapterExercises);
            }

            return ResponseInfo.success(null);
        }else {
            return ResponseInfo.error("您无权限创建课时");
        }

    }



    @Override
    public Map list(CourseChapterExercises courseChapterExercises, InputParam inputParam) {
        if(StringUtils.isEmpty(courseChapterExercises.getChapterId())){
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }

//        String jsonString = JSONObject.toJSONString(chapterList);
//        System.out.println(jsonString);
        //当前用户的信息
        User currentUser = userService.selectById(inputParam.getUserId());
        //若是学生要返回学生的答题记录，并清空答案与解析
        if(currentUser.getRoleType().equals(Role.STUDENT)) {

            List<CourseChapterExercises> stuRes = this.baseMapper.getByStuId(inputParam);
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("code", 200);
            resultMap.put("hasRecord",false);//前端判断要用到该键值
            for (CourseChapterExercises chapterExercises : stuRes) {
                if(chapterExercises.getStu()!=null &&
                        chapterExercises.getStu().getAnswer()!=null){
                    resultMap.put("hasRecord",true);
                }else {
                    //当学生做题时，若无答题记录，则清空答案与解析
                    chapterExercises.setAnswer(null);
                    chapterExercises.setReason(null);
                }
            }
            resultMap.put("data", stuRes);
            return  resultMap;
        }else {
            EntityWrapper<CourseChapterExercises> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("status",1);
            entityWrapper.eq("chapter_id",courseChapterExercises.getChapterId());
            entityWrapper.orderBy("num",true);
            List<CourseChapterExercises> chapterList = this.baseMapper.selectList(entityWrapper);
            return ResponseInfo.success(chapterList);

        }

    }

    @Override
    public Map dele(CourseChapterExercises exercises) {
        if(!StringUtils.isEmpty(exercises.getId())){
//            exercises.setStatus(0);
//            this.updateById(exercises);
            this.baseMapper.deleteById(exercises.getId());
        }
        return ResponseInfo.success(null);
    }

    @Override
    public Map getById(CourseChapterExercises courseChapterExercises, InputParam inputParam) {
        if(StringUtils.isEmpty(courseChapterExercises.getId())) {
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }else{
            CourseChapterExercises temp = this.selectById(courseChapterExercises.getId());
            return ResponseInfo.success(temp);
        }

    }

    @Override
    public Map stuSubmit(InputParam inputParam) {
        //学生批量提交习题
        if(StringUtils.isEmpty(inputParam.getUserId())
            ||StringUtils.isEmpty(inputParam.getChapterId())
                ||StringUtils.isEmpty(inputParam.getExerciseStr())) {
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }else {
            //先查出该课时的所有题目
            EntityWrapper<CourseChapterExercises> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("chapter_id",inputParam.getChapterId());
            entityWrapper.eq("status",1);
            List<CourseChapterExercises> chapterList = this.baseMapper.selectList(entityWrapper);
            if(chapterList.size()==0){
                return ResponseInfo.error(SystemParam.ERROR_PARAMS);
            }
            //题目要先拆分
            String[] exerciseArr = inputParam.getExerciseStr().split(",");
            //若提交的题目数量与习题不一致，则不让提交
            if(exerciseArr.length!=chapterList.size()){
                return ResponseInfo.error(SystemParam.ERROR_PARAMS);
            }
            //删除旧的答题记录
            EntityWrapper<CourseChapterExercisesStu> deleEntity = new EntityWrapper<>();
            entityWrapper.eq("chapter_id",inputParam.getChapterId());
            entityWrapper.eq("user_id",inputParam.getUserId());
            courseChapterExercisesStuService.delete(deleEntity);

            List<CourseChapterExercisesStu> resList = new ArrayList<>();
            for (String exerciseStr : exerciseArr) {
                //再拆分成id与答案
                String[] split = exerciseStr.split("-");
                if(split.length!=2){
                    return ResponseInfo.error(SystemParam.ERROR_PARAMS);
                }
                CourseChapterExercisesStu exercise= new CourseChapterExercisesStu();
                exercise.setExerciseId(Integer.valueOf(split[0]));
                exercise.setAnswer(split[1]);
                exercise.setCreateTime(new Date());
                exercise.setChapterId(inputParam.getChapterId());
                exercise.setUserId(inputParam.getUserId());
                exercise.setResult(verdict(chapterList,Integer.valueOf(split[0]),split[1]));
                resList.add(exercise);
            }

            String res=null;
            if(resList.size()>0){
                courseChapterExercisesStuService.insertBatch(resList);

                //统计答题的正确与错误数
                res = "本次答题共"+resList.size()+"题;";
                List<CourseChapterExercisesStu> correct= resList.stream()
                        .filter(stu -> stu.getResult().equals(1))
                        .collect(Collectors.toList());
                res+="正确数量："+correct.size()+"题;";
                res+="错误数量："+(resList.size()-correct.size())+"题。";

            }

            return ResponseInfo.success(res);
        }
    }
    //对学生的答案进行校验  1 正确，0 错误
    private Integer  verdict(List<CourseChapterExercises> chapterList,
                             Integer exerciseId,String answer){
        for (CourseChapterExercises courseChapterExercises : chapterList) {
            if(courseChapterExercises.getId().equals(exerciseId)
                    &&courseChapterExercises.getAnswer().equals(answer)){
                return 1;
            }
        }
        return 0;
    }
    @Override
    public Map getByStuId(InputParam inputParam) {
        if(StringUtils.isEmpty(inputParam.getUserId())
                ||StringUtils.isEmpty(inputParam.getChapterId())) {
            return ResponseInfo.error(SystemParam.ERROR_PARAMS);
        }else {
            return  ResponseInfo.success(this.baseMapper.getByStuId(inputParam));
        }
    }



}
